//
//  SEGChangePasswordViewController.m
//  ExcellentHome
//
//  Created by 梁昆 on 16/9/12.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGChangePasswordViewController.h"
#import <Commom/SEGEncryptRule.h>
#import <Commom/UITextField+Limit.h>
#import <Commom/SEGSafaKeyboard.h>
#import <Commom/SEGPasswordTextField.h>

#import "SEGChangePasswordViewModel.h"

@interface SEGChangePasswordViewController () <UITextFieldDelegate, SGETextFieldLimitDelegate>

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *line1View;
@property (nonatomic, strong) UIView *line2View;
@property (nonatomic, strong) UILabel *oldPasswordLabel;
@property (nonatomic, strong) UILabel *freshPasswordLabel;
@property (nonatomic, strong) UILabel *confirmPasswordLabel;
@property (nonatomic, strong) SEGPasswordTextField *oldPasswordText;
@property (nonatomic, strong) SEGPasswordTextField *freshPasswordText;
@property (nonatomic, strong) SEGPasswordTextField *confirmPasswordText;

///< 图形验证码输入框
@property (nonatomic, strong) UITextField *checkImgText;
///< 图形验证码图片
@property (nonatomic, strong) UIImageView *checkImgView;
///< 图形验证码刷新按钮
@property (nonatomic, strong) UIButton *freshCheckImgBtn;
@property (nonatomic, strong) UILabel *passwordRuleLabel;
/// 导航栏右侧确定按钮
@property (nonatomic, strong) UIButton *confirmButton;

/// viewModel
@property (nonatomic, strong) SEGChangePasswordViewModel *viewModel;

@end

@implementation SEGChangePasswordViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_bg;
    [self showCustomNavigationBackButton];
    self.title = @"修改密码";
    self.confirmButton = [self showCustomNavigationRightButtonWithColorTitle:@"确定" titleColor:kColor_T disabledColor:kColor_C];
    self.confirmButton.enabled = NO;
    [self setupUI];

    // 请求密码配置信息
    [self requestPasswordConfig];
    // 刷新验证码
    [self freshCheckImgBtnClick];
    // 绑定信号
    [self seg_bindSignal];
    
    //注册通知 监听用户截屏
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleUserDidTakeScreenshot:)
                                                 name:UIApplicationUserDidTakeScreenshotNotification
                                               object:nil];
    if (@available(iOS 11.0, *)) {
        // 监测当前设备是否处于录屏状态
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
        // 监听用户是否录屏
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleScreenCapturedDidChange:)
                                                     name:UIScreenCapturedDidChangeNotification
                                                   object:nil];
    }
}

#pragma mark - Bind
- (void)seg_bindSignal {
//    RACChannelTo(self.viewModel, checkImgStr) = self.checkImgText.rac_newTextChannel;
//    RAC(self.viewModel, oldPwdStr) = self.oldPasswordText.rac_textSignal;
//    RAC(self.viewModel, freshPwdStr) = self.freshPasswordText.rac_textSignal;
//    RAC(self.viewModel, confirmPwdStr) = self.confirmPasswordText.rac_textSignal;
}

#pragma mark - Load Data
// 请求密码配置
- (void)requestPasswordConfig {
    @weakify(self);
    [self.viewModel.reqConfigSignal subscribeNext:^(id result) {
        @strongify(self);
        self.passwordRuleLabel.text = result;
        NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
        paragraphStyle.lineSpacing = 8 - (self.passwordRuleLabel.font.lineHeight - self.passwordRuleLabel.font.pointSize);
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
        self.passwordRuleLabel.attributedText = [[NSAttributedString alloc] initWithString:result attributes:attributes];
    }];
}

#pragma mark - UI
- (void)setupUI {
    CGFloat cellHeight = 44;
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.view).mas_offset(15);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(44 * 4);
    }];

    [self.view addSubview:self.line1View];
    [self.line1View mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView).mas_offset(44);
        make.left.equalTo(self.view).mas_offset(5);
        make.right.equalTo(self.view).mas_offset(-5);
        make.height.mas_equalTo(0.5);
    }];

    [self.view addSubview:self.line2View];
    [self.line2View mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line1View).mas_offset(44);
        make.left.equalTo(self.view).mas_offset(5);
        make.right.equalTo(self.view).mas_offset(-5);
        make.height.mas_equalTo(0.5);
    }];

    [self.view addSubview:self.oldPasswordLabel];
    [self.oldPasswordLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView);
        make.bottom.equalTo(self.line1View.mas_top);
        make.left.equalTo(self.bottomView).mas_offset(10);
        make.width.mas_equalTo(80);
    }];

    [self.view addSubview:self.freshPasswordLabel];
    [self.freshPasswordLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line1View.mas_bottom);
        make.bottom.equalTo(self.line2View.mas_top);
        make.left.equalTo(self.bottomView).mas_offset(10);
        make.width.mas_equalTo(80);
    }];

    [self.view addSubview:self.confirmPasswordLabel];
    [self.confirmPasswordLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line2View.mas_bottom);
        make.height.mas_equalTo(cellHeight);
        make.left.equalTo(self.bottomView).mas_offset(10);
        make.width.mas_equalTo(80);
    }];

    [self.view addSubview:self.oldPasswordText];
    [self.oldPasswordText mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView).mas_offset(5);
        make.bottom.equalTo(self.line1View.mas_top).mas_offset(-5);
        make.left.equalTo(self.oldPasswordLabel.mas_right);
        make.right.mas_equalTo(-10);
    }];

    [self.view addSubview:self.freshPasswordText];
    [self.freshPasswordText mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line1View.mas_bottom).mas_offset(5);
        make.bottom.equalTo(self.line2View.mas_top).mas_offset(-5);
        make.left.equalTo(self.freshPasswordLabel.mas_right);
        make.right.mas_equalTo(-10);
    }];

    [self.view addSubview:self.confirmPasswordText];
    [self.confirmPasswordText mas_makeConstraints:^(MASConstraintMaker* make) {
        make.height.mas_equalTo(cellHeight);
        make.centerY.equalTo(self.confirmPasswordLabel);
        make.left.equalTo(self.confirmPasswordLabel.mas_right);
        make.right.mas_equalTo(-10);
    }];
    
    UIView *lineView3 = [[UIView alloc] init];
    lineView3.backgroundColor = kColor_L2;
    [self.bottomView addSubview:lineView3];
    [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.line2View.mas_left);
        make.right.equalTo(self.line2View.mas_right);
        make.height.mas_equalTo(0.5);
        make.top.mas_equalTo(cellHeight*3);
    }];
    
    // 图形验证码 刷新
    [self.bottomView addSubview:self.freshCheckImgBtn];
    [self.freshCheckImgBtn mas_makeConstraints:^(MASConstraintMaker* make) {
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(cellHeight);
        make.bottom.mas_equalTo(0);
        make.width.mas_equalTo(40);
    }];
    
    // 图形验证码 图片
    [self.bottomView addSubview:self.checkImgView];
    [self.checkImgView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.width.mas_equalTo(71 * kScaleWidth);
        make.height.mas_equalTo(29 * kScaleHeight);
        make.centerY.equalTo(self.freshCheckImgBtn);
        make.right.equalTo(self.freshCheckImgBtn.mas_left).offset(-15);
    }];
    
    // 图形验证码 输入
    [self.bottomView addSubview:self.checkImgText];
    [self.checkImgText mas_makeConstraints:^(MASConstraintMaker* make) {
        make.bottom.mas_equalTo(0);
        make.left.mas_equalTo(10);
        make.height.mas_equalTo(cellHeight);
        make.right.equalTo(self.checkImgView.mas_left).offset(-10);
    }];
    
    [self.view addSubview:self.passwordRuleLabel];
    [self.passwordRuleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.equalTo(self.bottomView.mas_bottom).offset(10);
        make.right.mas_equalTo(-10);
    }];
}

#pragma mark - NSNotification
- (void)handleUserDidTakeScreenshot:(NSNotification *)notification {
    [SEGAlertView showTmepMessageWithMessage:KDetectScreenShotTipMessage withtime:2];
}
- (void)handleScreenCapturedDidChange:(NSNotification *)notification {
    NSLog(@"%s %@", __func__, notification);
    if (@available(iOS 11.0, *)) {
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
    }
}

#pragma mark - Event
// 导航栏上，“确定” 按钮触发方法
- (void)onNavigationRightButtonClicked:(UIButton *)sender {
    @weakify(self);
    self.viewModel.oldPwdStr = self.oldPasswordText.text;
    self.viewModel.freshPwdStr = self.freshPasswordText.text;
    self.viewModel.confirmPwdStr = self.confirmPasswordText.text;
    self.viewModel.checkImgStr = self.checkImgText.text;
    [SVProgressHUD show];
    [self.viewModel.sureBtnSignal subscribeNext:^(NSDictionary *dic) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:dic[@"message"] withtime:1.5];
        [[SEGUhomeMediator sharedInstance] seg_pushToLoginViewController:dic];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        @strongify(self);
        if (error.code == 0) {
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        } else {
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason withtime:1.5];
            // 【等保改造】修改密码失败的时候就清空&刷新验证码
            [self freshCheckImgBtnClick];
        }
    }];
}
// 刷新图片验证码
- (void)freshCheckImgBtnClick {
    @weakify(self);
    self.checkImgText.text = @"";
    [self.viewModel.refreshImgSignal subscribeNext:^(UIImage *decodedImage) {
        @strongify(self);
        if (decodedImage) {
            [self.checkImgView setImage:decodedImage];
        } else {
            [self.checkImgView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        }
        // 确定按钮高亮状态
        [self updateSubmitButtonStatus];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        // 确定按钮高亮状态
         [self updateSubmitButtonStatus];
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - SGETextFieldLimitDelegate
- (void)limitTextFileDidChange:(UITextField *)textField {
    [self updateSubmitButtonStatus];
}
- (void)updateSubmitButtonStatus {
    if (self.oldPasswordText.text.length > 0 && self.freshPasswordText.text.length > 0 && self.confirmPasswordText.text.length > 0 && self.checkImgText.text.length > 0) {
        self.confirmButton.enabled = YES;
    } else {
        self.confirmButton.enabled = NO;
    }
}

#pragma mark - Getter
// 原密码，新密码，确认密码背后的白色背景框
- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = kColor_W;
    }
    return _bottomView;
}
// 第一根灰色分割线
- (UIView *)line1View {
    if (!_line1View) {
        _line1View = [[UIView alloc] init];
        _line1View.backgroundColor = kColor_L2;
    }
    return _line1View;
}
- (UIView *)line2View {
    if (!_line2View) {
        _line2View = [[UIView alloc] init];
        _line2View.backgroundColor = kColor_L2;
    }
    return _line2View;
}
// 三个开头的Label
- (UILabel *)oldPasswordLabel {
    if (!_oldPasswordLabel) {
        _oldPasswordLabel = [[UILabel alloc] init];
        [_oldPasswordLabel setText:@"原密码"];
        [_oldPasswordLabel setTextColor:kColor_2];
        [_oldPasswordLabel setFont:[UIFont systemFontOfSize:15]];
    }
    return _oldPasswordLabel;
}
- (UILabel *)freshPasswordLabel {
    if (!_freshPasswordLabel) {
        _freshPasswordLabel = [[UILabel alloc] init];
        [_freshPasswordLabel setText:@"新密码"];
        [_freshPasswordLabel setTextColor:kColor_2];
        [_freshPasswordLabel setFont:[UIFont systemFontOfSize:15]];
    }
    return _freshPasswordLabel;
}
- (UILabel *)confirmPasswordLabel {
    if (!_confirmPasswordLabel) {
        _confirmPasswordLabel = [[UILabel alloc] init];
        [_confirmPasswordLabel setText:@"确认密码"];
        [_confirmPasswordLabel setTextColor:kColor_2];
        [_confirmPasswordLabel setFont:[UIFont systemFontOfSize:15]];
    }
    return _confirmPasswordLabel;
}
// 输入手机号码textfield
- (SEGPasswordTextField *)oldPasswordText {
    if (!_oldPasswordText) {
        _oldPasswordText = [[SEGPasswordTextField alloc] init];
        [_oldPasswordText setTextColor:kColor_1];
        [_oldPasswordText setTintColor:kColor_T];
        [_oldPasswordText setFont:[UIFont systemFontOfSize:15]];
        [_oldPasswordText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"请输入原密码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _oldPasswordText.secureTextEntry = YES;
        _oldPasswordText.delegate = self;
        [_oldPasswordText configPasswordInputLimitWithDelegate:self currentView:self.view];
    }
    return _oldPasswordText;
}
// 输入验证码textfield
- (SEGPasswordTextField *)freshPasswordText {
    if (!_freshPasswordText) {
        _freshPasswordText = [[SEGPasswordTextField alloc] init];
        [_freshPasswordText setTextColor:kColor_1];
        [_freshPasswordText setTintColor:kColor_T];
        [_freshPasswordText setFont:[UIFont systemFontOfSize:15]];
        [_freshPasswordText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"请输入新密码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _freshPasswordText.secureTextEntry = YES;
        _freshPasswordText.delegate = self;
        [_freshPasswordText configPasswordInputLimitWithDelegate:self currentView:self.view];
    }
    return _freshPasswordText;
}
// 输入密码textfield
- (SEGPasswordTextField *)confirmPasswordText {
    if (!_confirmPasswordText) {
        _confirmPasswordText = [[SEGPasswordTextField alloc] init];
        [_confirmPasswordText setTextColor:kColor_1];
        [_confirmPasswordText setTintColor:kColor_T];
        [_confirmPasswordText setFont:[UIFont systemFontOfSize:15]];
        [_confirmPasswordText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"请确认新密码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _confirmPasswordText.secureTextEntry = YES;
        _confirmPasswordText.delegate = self;
        [_confirmPasswordText configPasswordInputLimitWithDelegate:self currentView:self.view];
    }
    return _confirmPasswordText;
}
- (UIButton *)freshCheckImgBtn {
    if (!_freshCheckImgBtn) {
        //发送语音验证码 按钮
        _freshCheckImgBtn = [[UIButton alloc] init];
        [_freshCheckImgBtn setTitle:@"换一张" forState:UIControlStateNormal];
        [_freshCheckImgBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
        [_freshCheckImgBtn setTitleColor:kColor_T forState:UIControlStateNormal];
        _freshCheckImgBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _freshCheckImgBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        //发送事件
        [_freshCheckImgBtn addTarget:self action:@selector(freshCheckImgBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _freshCheckImgBtn;
}
// 图片验证码
- (UITextField *)checkImgText {
    if (!_checkImgText) {
        _checkImgText = [[UITextField alloc] init];
        [_checkImgText setTextColor:kColor_1];
        [_checkImgText setFont:[UIFont systemFontOfSize:13]];
        _checkImgText.clearsOnBeginEditing = NO;
        _checkImgText.delegate = self;
        _checkImgText.clearButtonMode = UITextFieldViewModeNever;
        _checkImgText.autocorrectionType = UITextAutocorrectionTypeNo;
        [_checkImgText setTintColor:kColor_T];
        [_checkImgText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"图片验证码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        [_checkImgText setKeyboardType:UIKeyboardTypeWebSearch];
        [_checkImgText configImgCodeInputLimitWithDelegate:self];
    }
    return _checkImgText;
}
- (UIImageView *)checkImgView {
    if (!_checkImgView) {
        _checkImgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        [_checkImgView setUserInteractionEnabled:YES];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(freshCheckImgBtnClick)];
        [_checkImgView addGestureRecognizer:tap];
    }
    return _checkImgView;
}
- (UILabel *)passwordRuleLabel {
    if (!_passwordRuleLabel) {
        _passwordRuleLabel = [[UILabel alloc] init];
        _passwordRuleLabel.textColor = kColor_C;
        _passwordRuleLabel.textAlignment = NSTextAlignmentLeft;
        _passwordRuleLabel.font = kFont_13;
        _passwordRuleLabel.numberOfLines = 0;
    }
    return _passwordRuleLabel;
}
- (SEGChangePasswordViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGChangePasswordViewModel new];
    return _viewModel;
}

@end
